export const baseUrl: string = process.env.NODE_ENV === 'development' ? 'https://mini.wykji.cn/' : 'https://mini.wykji.cn/'
export const baseUrl2  = 'http://mall.wykji.cn/'
const header = {
	"x-sid": 120,
	"x-mid":13,
	"x-version": 1,
	//"X-Environment-UID":305030,
	"x-project": 'wanghou'
}
export const get = function (url: string, params?: any) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'GET',
			data: params,
			success: res => {
				resolve(res.data)
			},
			fail: err => {
				reject(err)
			},
		})
	})
}
export const post = function (url: string, params?: any) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'POST',
			data: params,
			header: {
				'content-type': 'application/json',
			},
			success: res => {
				resolve(res.data)
			},
			fail: err => {
				reject(err)
			},
		})
	})
}
export const put = function (url: string, params?: any) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'PUT',
			data: params,
			success: res => {
				resolve(res.data)
			},
			fail: err => {
				reject(err)
			},
		})
	})
}

export const upload = function (file: string) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl + 'Public/upload_file',
			filePath: file,
			name: 'file',
			header: {
				...header,
				'content-type': 'multipart/form-data',
			},
			success: res => {
				let data = JSON.parse(getStatusType(res))
				resolve(data)
			},
			fail: err => {
				reject(err)
			},
		})
	})
}
// 请求拦截器 用于请求前和响应后做一些处理
uni.addInterceptor('request', {
	invoke: args => {
		let domain = args.url.indexOf('mall/')===0?baseUrl2:baseUrl
		let url = args.url.replace('mall/','')
		args.url = domain + url
		
		args.header = {
			...args.header,
			...header
		}
		const token = uni.getStorageSync('token')
		if (token) {
			args.header = {
				...args.header,
				"x-token": token,
			}
		}
		//console.log('请求参数', args.url,args);
		return args
	},
	success: res => {
		return getStatusType(res)
	},
})
const getStatusType = (res: any) => {
	const status = res.statusCode
	let message = ''
	switch (status) {
		case 200:
			message = '请求成功'
			break
		case 400:
			message = '请求错误'
			break
		case 401:
			message = '请登录'
			break
		case 403:
			message = '拒绝访问'
			break
		case 404:
			message = `请求地址出错: ${res.url}`
			break
		case 408:
			message = '请求超时'
			break
		case 500:
			message = '服务器内部错误'
			break
		case 501:
			message = '服务未实现'
			break
		case 502:
			message = '网关错误'
			break
		case 503:
			message = '服务不可用'
			break
		case 504:
			message = '网关超时'
			break
		case 505:
			message = 'HTTP版本不受支持'
			break
		default:
			message = '请求失败'
	}
	if (status !== 200) {
		uni.showToast({
			title: message,
			icon: 'none',
			duration: 2000,
		})
	}
	return res.data
}
// export const baseUrl=baseUrl